package com.xuecheng.manage_course.service;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xuecheng.framework.domain.cms.response.CmsCode;
import com.xuecheng.framework.domain.course.CourseBase;
import com.xuecheng.framework.domain.course.CourseMarket;
import com.xuecheng.framework.domain.course.CoursePic;
import com.xuecheng.framework.domain.course.Teachplan;
import com.xuecheng.framework.domain.course.ext.CourseInfo;
import com.xuecheng.framework.domain.course.ext.TeachplanNode;
import com.xuecheng.framework.domain.course.request.CourseListRequest;
import com.xuecheng.framework.domain.course.response.AddCourseResult;
import com.xuecheng.framework.domain.course.response.CourseCode;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.model.response.*;
import com.xuecheng.manage_course.dao.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class CourseService {

//    创建dao层对象

    /**
     * 操作对象类的对象，自己定义的
     */
    @Autowired
    TeachplanMapper teachplanMapper;

    @Autowired
    CourseMapper courseMapper;

    /**
     * 课程计划的dao对象，是由springdata封装好的
     */
    @Autowired
    TeachplanRepository teachplanRepository;

    /**
     * 课程基本信息的dao对象，是由springdata封装好的
     */
    @Autowired
    CourseBaseRepository courseBaseRepository;

    @Autowired
    CourseMarketRepository courseMarketRepository;


    @Autowired
    CoursePicRepository coursePicRepository;
    /**
     * 查询课程计划
     * @param  courseId 课程id
     * @return 返回三层目录
     */
    public TeachplanNode findTeachplanList(String courseId){

        return teachplanMapper.selectList(courseId);
    }

    /**
     * 添加课程计划
     * @param teachplan 课程计划
     * @return 返回响应结果
     */
    @Transactional
    public ResponseResult addTeachplan(Teachplan teachplan) {

        //校验课程id和名称
        System.out.println(teachplan);
        if(teachplan == null || StringUtils.isEmpty(teachplan.getCourseid()) || StringUtils.isEmpty(teachplan.getPname())){
            //非法参数
            ExceptionCast.cast(CmsCode.INVALID_PARAM);
        }

        //取出id 和课程名称
        String courseId  = teachplan.getCourseid();

//        取出父节点的id
        String parentid = teachplan.getParentid();

        //如果父节点为空，则根据课程id，指定一个父节点
        if(StringUtils.isEmpty(parentid)){
            parentid = getTeachplanRoot(courseId);
        }

        Optional<Teachplan> teachplanOptional = teachplanRepository.findById(parentid);
        if(!(teachplanOptional.isPresent())){
            ExceptionCast.cast(CmsCode.INVALID_PARAM);
        }

        Teachplan teachplanParent = teachplanOptional.get();

        //此时这个节点已经定了，但是要指定它的上级节点是谁
        teachplan.setParentid(parentid);
        //未发布
        teachplan.setStatus("0");
        if("1".equals(teachplanParent.getGrade())){
            teachplan.setGrade("2");
        }else if("2".equals(teachplanParent.getGrade())){
            teachplan.setGrade("3");
        }

        teachplan.setCourseid(teachplanParent.getCourseid());
        teachplanRepository.save(teachplan);
        return new ResponseResult(CommonCode.SUCCESS);

    }

    /**
     * 得到课程计划的根节点
     * @param courseId 课程id
     * @return 返回根节点id
     */
    private String getTeachplanRoot(String courseId) {

        Optional<CourseBase> courseBaseOptional = courseBaseRepository.findById(courseId);
        //如果不存在，课程id是个非法的参数
        if(!courseBaseOptional.isPresent()){

            return null;
        }

        CourseBase courseBase1 = courseBaseOptional.get();
        List<Teachplan> parentList = teachplanRepository.findByCourseidAndParentid(courseId, "0");

        //如果不存在父节点，自己就是父节点
        if(parentList == null || parentList.size() == 0){
            Teachplan teachplan = new Teachplan();
            teachplan.setCourseid(courseId);
            teachplan.setPname(courseBase1.getName());
            teachplan.setParentid("0");
            teachplan.setStatus("0");
            teachplanRepository.save(teachplan);
            return teachplan.getId();
        }
        //如果存在父节点，则返回父节点
        Teachplan teachplan = parentList.get(0);
        return teachplan.getId();
    }


    /**
     * 课程列表的分页查询
     * @param page 页面数
     * @param size 页面大小
     * @param courseListRequest 请求参数
     * @return
     */
    public QueryResponseResult<CourseInfo> findCourseList(int page, int size, CourseListRequest courseListRequest){

        if(courseListRequest == null){
            courseListRequest = new CourseListRequest();
        }
        if(page < 0){
            page = 0;
        }
        if(size < 0){
            size = 10;
        }
//        设置分页参数
        PageHelper.startPage(page,size);
        Page<CourseInfo> courseListPage = courseMapper.findCourseListPage(courseListRequest);
        //得到查询列表
        List<CourseInfo> list = courseListPage.getResult();
        //拿到总记录数
        long total = courseListPage.getTotal();

        QueryResult<CourseInfo> courseInfoQueryResult = new QueryResult<>();
        courseInfoQueryResult.setList(list);
        courseInfoQueryResult.setTotal(total);
        return new QueryResponseResult<>(CommonCode.SUCCESS,courseInfoQueryResult);
    }


    @Transactional
    public AddCourseResult addCourseBase(CourseBase courseBase) {
        //课程默认为未发布
        courseBase.setStatus("202001");
        courseBaseRepository.save(courseBase);
        return new AddCourseResult(CommonCode.SUCCESS,courseBase.getId());
    }

    /**
     * 更新课程信息
     * @param id
     * @param courseBase
     * @return
     */
    public ResponseResult updateCourseBase(String id, CourseBase courseBase) {
        //根据课程id,查询到相对应地课程基础信息
        CourseBase courseBaseById = this.getCourseBaseById(id);
        if (courseBaseById == null) {
            ExceptionCast.cast(CmsCode.INVALID_PARAM);
        }

        //修改信息
        courseBaseById.setName(courseBase.getName());
        courseBaseById.setUsers(courseBase.getUsers());
        courseBaseById.setMt(courseBase.getMt());
        courseBaseById.setGrade(courseBase.getGrade());
        courseBaseById.setStudymodel(courseBase.getStudymodel());
        courseBaseById.setTeachmode(courseBase.getTeachmode());
        courseBaseById.setDescription(courseBase.getDescription());

        //调用dao对象进行保存
        CourseBase save = courseBaseRepository.save(courseBaseById);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * 根据课程id查询课程基础信息
     * @param courseId 课程id
     * @return 返回课程基本信息
     */
    public CourseBase getCourseBaseById(String courseId) {
        //调用封装好地dao对象
        Optional<CourseBase> courseBaseOptional = courseBaseRepository.findById(courseId);
        if(courseBaseOptional.isPresent()){
            return  courseBaseOptional.get();
        }
        return null;

    }

    public CourseMarket getCourseMarketById(String courseId) {
        Optional<CourseMarket> courseMarketOptional = courseMarketRepository.findById(courseId);
        if(courseMarketOptional.isPresent()){
            return courseMarketOptional.get();
        }
        return null;
    }

    public CourseMarket updateCourseMarket(String id, CourseMarket courseMarket) {
        CourseMarket courseMarketById = this.getCourseMarketById(id);
        //如果营销信息为空，则是第一次添加信息
        if(courseMarketById == null){
            courseMarketById = new CourseMarket();
            //利用spring提供地封装类进行复制
            BeanUtils.copyProperties(courseMarket,courseMarketById);
            //复制过去地信息只是营销信息，但是没有id
            courseMarketById.setId(id);
            courseMarketRepository.save(courseMarketById);
        }else {

            //进行课程营销信息地修改
            courseMarketById.setCharge(courseMarket.getCharge());
            courseMarketById.setStartTime(courseMarket.getStartTime());
            courseMarketById.setEndTime(courseMarket.getEndTime());
            courseMarketById.setPrice(courseMarket.getPrice());
            courseMarketById.setQq(courseMarket.getQq());
            courseMarketById.setValid(courseMarketById.getValid());

            //调用dao对象进行存储
            courseMarketRepository.save(courseMarketById);
        }
        return courseMarketById;
    }

    /**
     * 建立课程与图片的关系
     * @param courseId 课程id
     * @param pic 图片id
     * @return 返回建立关系的结果
     */
    @Transactional
    public ResponseResult saveCoursePic(String courseId,String pic){
        //先去mongodb中需要图片的信息，有，则直接使用，没有则新建
        Optional<CoursePic> picOptional = coursePicRepository.findById(courseId);
        CoursePic coursePic = null;
        if(picOptional.isPresent()){
           coursePic =  picOptional.get();
        }

        if(coursePic == null){
            coursePic = new CoursePic();
        }
        coursePic.setCourseid(courseId);
        coursePic.setPic(pic);

        //保存到mysql
        coursePicRepository.save(coursePic);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    public CoursePic findCoursePic(String courseId) {
        Optional<CoursePic> optional = coursePicRepository.findById(courseId);
        if (!optional.isPresent()) {
            //返回异常，提示查询的课程图片信息为空
            ExceptionCast.cast(CourseCode.COURSE_SELECT_COURSEPICISNULL);
        }
        return optional.get();
    }

    /**
     * 删除课程图片
     * @param courseId 课程id
     * @return 返回响应结果
     */
    @Transactional
    public ResponseResult deleteCoursePic(String courseId){
        //大于0,删除成功，返回0，返回删除失败
        long result = coursePicRepository.deleteByCourseid(courseId);
        if(result > 0){
            return new ResponseResult(CommonCode.SUCCESS);
        }
        return new ResponseResult(CommonCode.FAIL);
    }

}
